package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.UserService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
@Slf4j
public class ReportServiceImpl implements ReportService {


    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;



    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate startDate, LocalDate endDate) {
        //当前集合 存储从beginDate到endDate的每一天
        List<LocalDate> dateList = new ArrayList<>();

        //当前集合 存储从beginDate到endDate的每一天的营业额
        dateList.add(startDate);
        while (!startDate.equals(endDate)){ //当startDate等于endDate时退出循环
            //获取startDate的下一天
            startDate = startDate.plusDays(1);
            dateList.add(startDate); //
        }


        String join = StringUtils.join(dateList, ",");


        //查询每天的营业额
        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate date : dateList) {
            //查询状态为已完成的订单
            //select sum(amount) from orders where status=5 and order_time between '2021-01-01' and '2021-01-01';
            LocalDateTime begin = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime end = LocalDateTime.of(date, LocalTime.MAX);

            Map map=new HashMap();
            map.put("status", Orders.COMPLETED);
            map.put("begin",begin);
            map.put("end",end);
            Double turnover = orderMapper.sumByMap(map);

            //如果没有订单则返回0.0
            if(turnover==null) turnover=0.0;

            turnoverList.add(turnover);
        }

        return TurnoverReportVO
                .builder()
                .dateList(join)
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();
    }


    /*
     * 统计指定时间内的用户增长情况
     * */
    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        //当前集合 存储从beginDate到endDate的每一天
        List<LocalDate> dateList = new ArrayList<>();

        dateList.add(begin);
        while (!begin.equals(end)){ //当begin等于end时退出循环
            //获取begin的下一天
            begin = begin.plusDays(1);
            dateList.add(begin); //
        }


        //查询每天的新增用户数
        List<Integer> newUserList = new ArrayList<>();
        //查询当前天总的用户数
        List<Integer> totalUserList = new ArrayList<>();

        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime= LocalDateTime.of(date, LocalTime.MAX);
            //查询当天新增的用户数

            Map map=new HashMap();
            map.put("end",endTime);

            //总用户数量
            Integer totalUser = userMapper.countByMap(map);

            //当天新增用户数量
            map.put("begin",beginTime);
            Integer newUser = userMapper.countByMap(map);

            //如果没有新增用户则返回0
            if(newUser==null) newUser=0;

            newUserList.add(newUser);
            totalUserList.add(totalUser);
        }

        return UserReportVO
                .builder()
                .dateList(StringUtils.join(dateList, ","))
                .newUserList(StringUtils.join(newUserList, ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .build();

    }

    @Override
    public OrderReportVO getOrderStatistics(LocalDate begin, LocalDate end) {
        //当前集合 存储从beginDate到endDate的每一天
        List<LocalDate> dateList = new ArrayList<>();

        dateList.add(begin);
        while (!begin.equals(end)){ //当begin等于end时退出循环
            //获取begin的下一天
            begin = begin.plusDays(1);
            dateList.add(begin); //
        }


        List<Integer> orderCountList = new ArrayList<>();
        List<Integer> validOrderCountList = new ArrayList<>();
        for(LocalDate date : dateList){
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime= LocalDateTime.of(date, LocalTime.MAX);

            //查询每天的订单数
            Integer orderCount = getOrderCount(beginTime, endTime, null);
            //查询每天的有效订单数
            Integer validOrderCount = getOrderCount(beginTime, endTime, Orders.COMPLETED);

            //添加到集合中
            orderCountList.add(orderCount);
            validOrderCountList.add(validOrderCount);
        }

        //计算总订单数
        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();
        //计算有效订单数
        Integer validTotalOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();

        //计算订单完成率
        Double orderRate = 0.0;
        if(totalOrderCount!=0) orderRate = (double) validTotalOrderCount/totalOrderCount;

        return OrderReportVO
                .builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCountList(StringUtils.join(orderCountList, ","))
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validTotalOrderCount)
                .orderCompletionRate(orderRate)
                .build();
    }


    /*
    * 根据条件统计订单数量
    * */
    private Integer getOrderCount(LocalDateTime begin, LocalDateTime end,Integer status) {
        Map map=new HashMap();
        map.put("status",status);
        map.put("begin",begin);
        map.put("end",end);

        return orderMapper.countByMap(map);
    }

    /*
     * 统计指定时间区域内的销量排名前10
     * */
    @Override
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime= LocalDateTime.of(end, LocalTime.MAX);


        List<GoodsSalesDTO> salesTop10 = orderMapper.getSalesTop10(beginTime, endTime);


        //获取商品名称列表
        //什么语法？
        List<String> names = salesTop10.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        //获取商品销量列表
        List<Integer> numbers = salesTop10.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());

        return SalesTop10ReportVO
               .builder()
               .nameList(StringUtils.join(names, ","))
               .numberList(StringUtils.join(numbers, ","))
               .build();
    }

    public void exportBusinessData(HttpServletResponse response){
        //查询数据库，获取营业数据
        LocalDate dateBegin = LocalDate.now().minusDays(30);
        LocalDate dateEnd = LocalDate.now().minusDays(1);
        LocalDateTime begin = LocalDateTime.of(dateBegin, LocalTime.MIN);
        LocalDateTime end = LocalDateTime.of(dateEnd, LocalTime.MAX);

        //查询概览数据
        BusinessDataVO businessDataVO = workspaceService.getBusinessData(begin, end);

        //通过POI将数据写入Excel文件中
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        try {
            XSSFWorkbook excel = new XSSFWorkbook(in);


            //获取表格标签页
            XSSFSheet sheet = excel.getSheet("Sheet1");
            //填充数据--时间
            sheet.getRow(1).getCell(1).setCellValue("时间"+dateBegin+"至"+dateEnd);

            //填充数据--营业额
            //获取第四行
            XSSFRow row = sheet.getRow(3);
            row.getCell(2).setCellValue(businessDataVO.getTurnover());
            row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessDataVO.getNewUsers());

            //获得第5行
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            row.getCell(4).setCellValue(businessDataVO.getUnitPrice());

            //填充明细数据
            for(int i=0;i<30;i++){
                LocalDate date = dateEnd.plusDays(i);

                //查询每一天的数据
                workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
                //填充数据
                row=sheet.getRow(i+7);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessDataVO.getTurnover());
                row.getCell(3).setCellValue(businessDataVO.getValidOrderCount());
                row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessDataVO.getUnitPrice());
                row.getCell(6).setCellValue(businessDataVO.getNewUsers());
            }


            //通过输出流将excel文件输出到浏览器中
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);

            //关闭流
            out.close();
            in.close();
            excel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }
}
